<?php

namespace app\common\service;

use think\facade\Db;

/**
 * Class VipService
 * @package app\common\service
 */
class VipService
{
    /**
     * 获取所有VIP配置
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList()
    {
        return Db::table('vip')->order('sort', 'desc')->select();
    }

    /**
     * 获取指定VIP配置
     * @param $id
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOne($id)
    {
        return Db::table('vip')->where('id', $id)->find();
    }

    /**
     * 薪资/更新一条VIP数据
     * @param $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save($data)
    {
        if ($data['id']) {
            if (!$vip = $this->getOne($data['id'])) {
                throw new \Exception('不存在的VIP数据');
            }
            return !!Db::table('vip')->save($data);
        } else {
            unset($data['id']);
            $id = Db::table('vip')->insert($data, true);
            if (!$id) {
                throw new \Exception('VIP数据添加失败');
            }
            return true;
        }
    }

    /**
     * 删除VIP数据
     * @param $id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete($id)
    {
        if (!$this->getOne($id)) {
            throw new \Exception('不存在的VIP数据');
        }
        return !!Db::table('vip')->where('id', $id)->delete();
    }
}